package com.weixin.web;

import com.agent.entity.PicWord;
import com.agent.service.IPicWordService;
import com.agent.util.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/weixin/picWord")
@Slf4j
public class WXPicWordController {

    @Autowired
    private IPicWordService picWordService;


    @RequestMapping("/download/{id}")
    public void download(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PicWord picWord = picWordService.getPicWord(id);
        File file = new File(picWord.getPicUrl());
        if(file.exists()){
            //设置MIME类型
            response.setContentType("application/octet-stream");
            //或者为response.setContentType("application/x-msdownload");
            //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
            response.addHeader("Content-disposition", "attachment;filename="+new String(file.getName().getBytes(), "ISO-8859-1"));
            InputStream inputStream=new FileInputStream(file);
            ServletOutputStream outputStream=response.getOutputStream();
            byte[] bs=new byte[1024];
            while((inputStream.read(bs)>0)){
                outputStream.write(bs);
            }
            outputStream.close();
            inputStream.close();
        }
    }

    @RequestMapping(value = "/normalPicWords" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> normalPicWords(PicWord picWord){
        try{
            List<PicWord> picWordList = picWordService.getPicWordList(picWord);
            Map<String, Object> successResult = ResponseData.getSuccessResult();
            successResult.put(ResponseData.DATA,picWordList);
            return successResult;
        }catch (Exception e){
            log.error("com.weixin.web.WXPicWordController.normalPicWords error |",e);
            return ResponseData.getErrorResult("获取常用选项失败");
        }
    }
}
